package com.shadow.cloud.dap7.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shadow.cloud.common.bo.R;
import com.shadow.cloud.dap7.bo.DictionaryQuery;
import com.shadow.cloud.dap7.entity.Dictionary;
import com.shadow.cloud.dap7.service.DictionaryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;

/**
 * Dictionary Controller
 *
 */
@RestController
@RequestMapping("dic/v1")
public class DictionaryController {

    @Resource
    private DictionaryService dictionaryService;

    /**
     * 新增数据字典
     *
     * @param dictionary 字典对象
     * @return {@link R}
     **/
    @PostMapping("/save")
    public R save(@RequestBody @Valid final Dictionary dictionary) {
        if (1 == dictionaryService.saveDictionary(dictionary)) {
            return R.success();
        }
        return R.fail();
    }

    /**
     * 删除数据字典.
     *
     * @param id 主键id
     * @return {@link R}
     **/
    @PostMapping("/delete/{id}")
    public R delete(@PathVariable String id) {
        if (1 == dictionaryService.delete(id)) {
            return R.success();
        }
        return R.fail();
    }

    /**
     * 更新数据字典
     *
     * @param dictionary 字典对象
     * @return {@link R}
     **/
    @PostMapping("/update")
    public R update(@RequestBody @Valid final Dictionary dictionary) {
        dictionary.setModifyTime(LocalDateTime.now());
        if (1 == dictionaryService.update(dictionary)) {
            return R.success();
        }
        return R.fail();
    }

    /**
     * 获取字典数据列表
     *
     * @param dictionaryQuery 字典查询对象
     * @return {@link R}
     **/
    @GetMapping("/getDictionaryList")
    public R getDictionaryList(final DictionaryQuery dictionaryQuery) {
        final IPage<Dictionary> dictionaryList = dictionaryService.getDictionaryList(dictionaryQuery);
        return R.successForLayUi(dictionaryList.getRecords(), 1);
    }

    /**
     * 获取字典数据
     *
     * @param id 字典主键
     * @return {@link R}
     **/
    @GetMapping("/getDictionary/{id}")
    public R getDictionaryList(@PathVariable final String id) {
        final Dictionary dictionary = dictionaryService.getById(id);
        return R.success(R.SUCCESS_MSG, dictionary);
    }

    /**
     * 数据字典唯一性验证
     *
     * @param dictionary 字典
     * @return {@link R}
     **/
    @PostMapping("/isExists")
    public R isExist(@RequestParam Dictionary dictionary) {
        final String name = dictionary.getDictName();
        final String value = dictionary.getDictValue();
        final String parentId = dictionary.getParentId();
        if (StringUtils.isNoneBlank(name, value, parentId)) {
            boolean isExist = dictionaryService.isExists(name, value, parentId);
            return R.success(R.SUCCESS_MSG, isExist);
        }
        return R.fail("RStatusEnums.PARAM_IS_BLANK");
    }
}

